using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace Jerry.UiFrame
{
    public class JButton : Button, IComponent
    {
        /// <summary>
        /// 按住多久开始调用
        /// </summary>
        public float holdTime = 1f;

        /// <summary>
        /// 重复调用的频率
        /// </summary>
        public float repeatRate = 0.3f;
        
        /// <summary>
        /// 按钮点击音效
        /// </summary>
        public string clickSound = null;

        public UnityEvent onLongPress;
        public UnityEvent onPressRepeat; //长按一直调用
        public new UnityEvent onClick;
        public UnityEvent onBtnDown;
        public UnityEvent onBtnUp;
        
        private bool _isPointerDown = false;
        private float _downTime;

        public override void OnPointerDown(PointerEventData eventData)
        {
            if(!IsInteractable())
                return;
            if (string.IsNullOrEmpty(clickSound))
            {
                if (UIConfig.BtnClickSound)
                    UIConfig.GetAudioSource().PlayOneShot(UIConfig.BtnClickSound);
            }
            else
            {
               var clip = UIConfig.GetLoader().LoadExternal<AudioClip>(clickSound);
               UIConfig.GetAudioSource().PlayOneShot(clip);
            }
           
            _isPointerDown = true;
            _downTime = Time.time;
            Invoke(nameof(LongPressRoutine), holdTime);
            InvokeRepeating(nameof(InvokeRepeating), holdTime, repeatRate);
            onBtnDown.Invoke();
            base.OnPointerDown(eventData);
        }

        public override void OnPointerUp(PointerEventData eventData)
        {
            if(!IsInteractable())
                return;
            _isPointerDown = false;
            if (Time.time - _downTime < holdTime)
            {
                onClick.Invoke();
            }

            onLongPress = null;
            onPressRepeat = null;
            onBtnUp?.Invoke();
            base.OnPointerUp(eventData);
        }

        private void LongPressRoutine()
        {
            if (_isPointerDown)
            {
                onLongPress?.Invoke();
            }
        }

        private void InvokeRepeating()
        {
            if (_isPointerDown)
            {
                onPressRepeat?.Invoke();
            }
        }

        public void SetVisible(bool bVisible)
        {
            gameObject.SetActive(bVisible);
        }

        public T GetChild<T>(string childName) where T : IComponent
        {
            var comp = transform.Find(childName).GetComponent<IComponent>();
            return (T)comp;
        }
    }
}